package com.chenl.provider.DEMOS.日志相关.全链路日志以及Spring线程池装饰器的使用;

import com.alibaba.fastjson.JSONObject;
import com.chenl.provider.util.TtlThreadLocal;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.Map;

@Slf4j
//@Configuration
public class FeignReqInterceptor implements RequestInterceptor {

    /**
     * 请求拦截器,使用feign进行调用时,请求头中注入当前已记录的所有日志
     * @param requestTemplate
     */
    @Override
    public void apply(RequestTemplate requestTemplate) {
        HttpServletRequest httpServletRequest = this.getHttpServletRequest();
        if (null != httpServletRequest) {
//            requestTemplate.header("log", URLEncoder.encode(JSONObject.toJSONString(LogThreadLocal.get())));
            requestTemplate.header("traceId", TtlThreadLocal.get().get("traceId"));
            requestTemplate.header("x-dcop-app-secret", "f12e1d0e8bab36295d162e763c24e1b5259710be14524977f4872f86b0098354");
//            Map<String, Collection<String>> headers = requestTemplate.headers();
//            if (headers.get("Content-Type")== null){
//                requestTemplate.header("Content-Type","application/x-www-form-urlencoded");
//            }
//            requestTemplate.header("Content-type", "application/json");
        }
    }

    private HttpServletRequest getHttpServletRequest() {
        try {
            return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
